"use strict";

const Service = require("egg").Service;
const md5 = require("md5");
const { v1: uuidv1 } = require("uuid");
class UserService extends Service {
  // 用户登录
  async login({ userName, password }) {
    const { app, ctx } = this;
    try {
      const data = await app.model.User.findOne({
        where: {
          userName
        },
        attributes: ["id", "userId", "password", "userName", "phone"]
      });
      if (data) {
        if (md5(`${password}${data.userId}`) === data.password) {
          const tokenDate = new Date().getTime();
          // 存token登录时间
          await app.model.Tokendate.update(
            {
              tokenDate: tokenDate
            },
            {
              where: {
                userId: data.userId
              }
            }
          );
          const ip = (
            ctx.req.headers["x-forwarded-for"] || // 判断是否有反向代理 IP
            ctx.req.connection.remoteAddress || // 判断 connection 的远程 IP
            ctx.req.socket.remoteAddress || // 判断后端的 socket 的 IP
            ctx.req.connection.socket.remoteAddress
          ).replace("::ffff:", "");
          await app.model.LoginLog.create({
            ip,
            ua: ctx.get("user-agent")
          });

          const token = app.jwt.sign(
            { userId: data.userId, tokenDate },
            app.config.jwt.secret,
            {
              expiresIn: app.config.jwt.expiresIn
            }
          );

          return {
            code: 200,
            data: {
              id: data.id,
              tokenDate,
              userId: data.userId,
              userName: data.userName,
              phone: data.phone,
              token
            },
            message: "登录成功"
          };
        } else {
          return {
            code: 405,
            message: "密码错误"
          };
        }
      } else {
        return {
          code: 405,
          message: "用户名错误"
        };
      }
    } catch (error) {
      return { userName, password };
    }
  }
  // 新增用户
  async addUser(params) {
    const { app } = this;
    try {
      params.userId = uuidv1();
      // params.userId = UUID.replace(/-/g, ""); // 去掉-字符，使用空格代替
      params.password = md5(`${params.password}${params.userId}`);
      const data = await app.model.User.create(params);

      if (data) {
        return {
          code: 200,
          message: "新增用户成功"
        };
      }
    } catch (error) {
      return await app.Lostconnection(error.message);
    }
  }

  // 获取用户数据
  async getUserList({ pageSize, page }) {
    const { app } = this;
    let limit = Number(pageSize) || 10; // 当页条数
    let offset = Number(pageSize) * (Number(page) - 1) || 0; // 开始下标
    try {
      const data = await app.model.User.findAll({
        limit,
        offset
      });
      const total = await app.model.User.count();
      return {
        code: 200,
        data,
        page: offset + 1,
        pageSize: limit,
        total,
        message: "获取获取用户成功"
      };
    } catch (error) {
      return await app.Lostconnection(error.message);
    }
  }
  token({ token }) {
    const { app } = this;

    const tokens = app.jwt.sign(
      { userId: token, name: 12212 },
      app.config.jwt.secret,
      {
        expiresIn: app.config.jwt.expiresIn
      }
    );
    return {
      code: 200,
      tokens,
      message: "获取token成功"
    };
  }
  isToken({ token }) {
    const { app } = this;
    try {
      const user = app.jwt.verify(token, app.config.jwt.secret);
      console.log("debug log --> ", user);
      return {
        code: 200,
        message: user
      };
    } catch (err) {
      let fail =
        err.name === "TokenExpiredError"
          ? "token 已过期! 请重新获取令牌"
          : "Token 令牌不合法!";
      return {
        code: 403,
        message: fail
      };
      // tokenDate
    }
  }
}
module.exports = UserService;
